package cn.com.chengmandian.bike.controller;


import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.bike.model.EbDepositRecord;
import cn.com.chengmandian.bike.model.EbRideOrder;
import cn.com.chengmandian.bike.service.IEbDepositRecordService;
import cn.com.chengmandian.bike.service.IEbRideOrderService;
import cn.com.chengmandian.core.redis.service.RedisService;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.pojo.LoginUser;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.service.bike.constants.RideOrderStatusEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 电单车运营-押金记录 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2023-11-16
 */
@Api(tags = "押金记录")
@RestController
@RequestMapping("/deposit/record")
public class EbDepositRecordController {

    @Autowired
    private IEbDepositRecordService depositRecordService;

    @Autowired
    private IEbRideOrderService rideOrderService;

    @Autowired
    private RedisService redisService;

    @ApiOperation("押金退款")
    @PostMapping("/refund")
    public AjaxResult refund(){
        AgentUser agentUser = AuthUtil.getAgentUser();
        EbDepositRecord depositRecord = depositRecordService.getByMember(agentUser.getId());
        Assert.notNull(depositRecord, "暂无押金可退");
        String redisKey = "CMD:BIKE:DEPOSIT:RECORD:".concat(depositRecord.getId().toString());
        if(redisService.hasKey(redisKey)){
            throw new BadResponseException("请一分钟后再次操作");
        }
        EbRideOrder rideOrder = rideOrderService.getOne(new LambdaQueryWrapper<EbRideOrder>()
                .eq(EbRideOrder::getMemberId, agentUser.getId())
                .in(EbRideOrder::getStatus, RideOrderStatusEnum.PAUSE.getCode(), RideOrderStatusEnum.RIDING.getCode(), RideOrderStatusEnum.CONFIRM.getCode())
                .last("limit 0,1"));
        Assert.isNull(rideOrder, "您有骑行中或待支付订单，暂不支持退押金");

        LoginUser loginUser = new LoginUser();
        loginUser.setId(agentUser.getId());
        loginUser.setName(agentUser.getName());
        depositRecordService.refund(depositRecord, "用户自助退款", LocalMapUtil.getAgentInfo(), loginUser);
        redisService.set(redisKey, depositRecord.getId(), 60);
        return AjaxResult.success("退款成功");
    }
}
